from typing import Dict
from service.stock_view_service import StockViewService
from service.strategy_query_service import StrategyViewQueryService
from views.common.style_sheet import StyleSheet
from views.common.translator import Translator
from views.template_page_view import BasePageTemplateView, MainCardTemplate
from PyQt6.QtGui import QFileSystemModel
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import (
    QHBoxLayout,
    QTreeWidgetItem,
    QTreeWidgetItemIterator,
    QFrame,
    QVBoxLayout
)
from qfluentwidgets import TreeWidget, setTheme, Theme, TreeView


class StrategyGroupView(BasePageTemplateView):
    """Scroll interface"""

    def __init__(self, parent=None):
        t = Translator()
        super().__init__("StrategyGroupView", parent=parent)

    def doInitAndUpdate(self):

        strategy_service = StrategyViewQueryService()
        self.strategy_info = strategy_service.get_strategy_list()

        self.viewService = StockViewService()
        level1_HLayout = QHBoxLayout()
        self.addTableTemplate(
            "风险板块报表",
            self.tablePlatesStockRisk,
            self.getBaseParam,
            1,
            level1_HLayout,
        )

        frame = TreeFrame(self, True)
        card = MainCardTemplate("策略列表", frame, 1, self.view)
        level1_HLayout.addWidget(card, 1, Qt.AlignmentFlag.AlignTop)
        self.addOutLayout(level1_HLayout)

    def tablePlatesStockRisk(self, params: Dict[str, str]) -> str:
        return self.viewService.search_all_strategy(params.values)

    def getStrategyParam(self) -> Dict[str, str]:
        return {"stockCode": "peak_and_decline"}


class Frame(QFrame):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.hBoxLayout = QHBoxLayout(self)
        self.hBoxLayout.setContentsMargins(0, 8, 0, 0)

        self.setObjectName("frame")
        StyleSheet.VIEW_INTERFACE.apply(self)

    def addWidget(self, widget):
        self.hBoxLayout.addWidget(widget)


class TreeFrame(Frame):

    def __init__(self, parent=None, enableCheck=False):
        super().__init__(parent)
        self.selected_items = set()  # 实时跟踪选中项的集合
        self.tree = TreeWidget(self)
        self.tree.setHeaderHidden(True)
        self.tree.itemChanged.connect(self.on_item_changed)  # 信号连接
        layout = QVBoxLayout(self)
        layout.addWidget(self.tree)

        # 添加树结构
        self.add_tree_items(enableCheck)

        self.setFixedSize(300, 380)

    def add_tree_items(self, enableCheck):
        """
        初始化树结构，并设置复选框状态。
        """
        item1 = QTreeWidgetItem([self.tr("JoJo 1 - Phantom Blood")])
        item1.addChildren([
            QTreeWidgetItem([self.tr("Jonathan Joestar")]),
            QTreeWidgetItem([self.tr("Dio Brando")]),
            QTreeWidgetItem([self.tr("Will A. Zeppeli")]),
        ])
        self.tree.addTopLevelItem(item1)

        item2 = QTreeWidgetItem([self.tr("JoJo 3 - Stardust Crusaders")])
        item21 = QTreeWidgetItem([self.tr("Jotaro Kujo")])
        item21.addChildren([
            QTreeWidgetItem([self.tr("空条承太郎")]),
            QTreeWidgetItem([self.tr("空条蕉太狼")]),
            QTreeWidgetItem([self.tr("阿强")]),
            QTreeWidgetItem([self.tr("卖鱼强")]),
            QTreeWidgetItem([self.tr("那个无敌的男人")]),
        ])
        item2.addChild(item21)
        self.tree.addTopLevelItem(item2)

        self.tree.expandAll()

        if enableCheck:
            self.enable_checkable_items()

    def enable_checkable_items(self):
        """
        为所有项添加复选框。
        """
        it = QTreeWidgetItemIterator(self.tree)
        while it.value():
            it.value().setCheckState(0, Qt.CheckState.Unchecked)
            it.value().setFlags(it.value().flags() | Qt.ItemIsUserCheckable)
            it += 1

    def on_item_changed(self, item, column):
        """
        当树项的复选框状态改变时更新选中项集合。
        """
        if item.checkState(0) == Qt.CheckState.Checked:
            self.selected_items.add(item.text(0))
        else:
            self.selected_items.discard(item.text(0))

        AntLogger.info(f"当前选中项: {self.selected_items}")
